package com.wuchao.controller;

import com.wuchao.service.serviceImpl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author wuchao66
 * @Date 2022/7/7 10:20
 * @Version 1.0
 */
@WebServlet(name = "ServletUserController",urlPatterns = "/ServletUserController"
,initParams = {@WebInitParam(name = "cc",value = "ccc")})
public class ServletUserController extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//乱码问题
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //out对象
        PrintWriter out = response.getWriter();//文件流
        //刷新缓存区 关闭
        out.flush();
        out.close();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //乱码问题
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //out对象
        PrintWriter out = response.getWriter();//文件流
        out.println("<script>");
        out.println("alert(\"我来搞事的\")");
        out.println("</script>");
        //刷新缓存区 关闭
        System.out.println("当前中的："+this.getServletConfig().getInitParameter("cc").toString());
        System.out.println("后台xml中："+this.getServletContext().getInitParameter("t151").toString());

        String op = request.getParameter("op");
        if(op!=null){//curd
            ServiceImpl service = new ServiceImpl();
            if(op.equals("delete")){
              int id =Integer.parseInt(request.getParameter("id"));
                int update = service.update("delete from user where id=?", id);
            if(update>0){//请求记得路径
                request.getRequestDispatcher("demo6/main.jsp?isdelete1=t").forward(request,response);
                }else{//重定向不知道地址要request帮忙
                    response.sendRedirect(request.getContextPath()+"/demo6/main.jsp?isdelete2=t");
                }
            }else if(op.equals("page")){
                int id =Integer.parseInt(request.getParameter("pageNum"));
                int count=service.isLoading("select count(1) from user");
                request.getRequestDispatcher("demo6/main.jsp?pageNum="+id+"&count="+count).forward(request,response);
            }
        }else{//第一次来
            request.getRequestDispatcher("demo6/main.jsp").forward(request,response);
        }
        out.flush();
        out.close();

    }
    public void init(){
        System.out.println("初始化");
    }
    public void destroy(){
        System.out.println("摧毁");
    }
}
